<?php

namespace app\admin\controller\buchang;

use app\admin\model\lists\One;
use app\common\controller\Backend;
use think\Config as thconfig;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
use think\response\Json;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Baoan extends Backend
{

    /**
     * Baoan模型对象
     * @var \app\admin\model\buchang\Baoan
     */
    protected $model = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\buchang\Baoan;
        $this->view->assign("statusList", $this->model->getStatusList());
        $jigoudata = [''=>'请选择业务来源','直属业务'=>'直属业务','直接业务'=>'直接业务','分支机构'=>'分支机构','合作商'=>'合作商','查勘机构'=>'查勘机构','招商业务'=>'招商业务','合作业务 '=>'合作业务'];
        $this->view->assign('jigoudata', $jigoudata);
        $site = thconfig::get('site');
        $this->view->assign('chexing', $site['chexing']);
        $this->view->assign('xingzhi', $site['xingzhi']);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
//        $where1['baoan_status'] = ['<>', 1];
        $list = $this->model
            ->where($where)
            ->with(['zuzhi'])
//            ->where($where1)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->assign('selectMenu', Loader::model('Zuzhi')->selectMenu());
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if (isset($params['province']) && isset($params['city']) && isset($params['area'])) {
                $area_name = Db::name('area')->whereIn('id', [$params['province'], $params['city'], $params['area']])->column('name');
                $params['address'] = implode('', $area_name) . $params['address'];
                unset($params['province']);
                unset($params['city']);
                unset($params['area']);
            }
            $params['baoan_time'] = strtotime($params['baoan_time']);
            $params['chuxian_time'] = strtotime($params['chuxian_time']);
            $params['yw_hetong_time'] = strtotime($params['yw_hetong_time']);
            $params['plan_endtime'] = strtotime($params['plan_endtime']);
            $params['plan_strattime'] = strtotime($params['plan_strattime']);
            $params['baoan_id'] = zancun("baoan", "baoan_id", "MYBA");
            $params['bianhao'] = zancun("baoan", "bianhao", "BC");
            $admin = $this->auth->getUserInfo();
            $params['yw_enter_peo'] = $admin['username'];
            $params['status'] = 0;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 新增页面浏览服务单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function liulan()
    {
        $data = $_POST;
        $where = [];
        if($data['car_num']){
            $where['car_num'] = ['like',"%$data[car_num]%"];
        }
        if($data['tong_number']){
            $where['tong_number'] = ['like',"%$data[tong_number]%"];
        }
        if($data['learned_name']){
            $where['learned_name'] = ['like',"%$data[learned_name]%"];
        }
        if($data['car_vin']){
            $where['car_vin'] = ['like',"%$data[car_vin]%"];
        }
        $field = 'id,tong_number,car_num,car_vin,learned_name,yw_hetong_time,plan_endtime,learned_phone,yw_class,yw_belonger,plan_strattime';
        $res = Db::name('list_one')->where($where)->where('status',5)->field($field)->select();
        foreach ($res as &$v) {
            $v['yw_hetong_time'] = date('Y-m-d', $v['yw_hetong_time']);
            $v['plan_endtime'] = date('Y-m-d', $v['plan_endtime']);
            $v['plan_strattime'] = date('Y-m-d', $v['plan_strattime']);
        }
        $this->success('', '', $res);
    }

    /**
     * 详情
     * @param $ids
     * @return void
     * @throws \think\exception\DbException
     */
    public function details($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        $row['yw_class'] = Db::name('zuzhi')->where('id', $row['yw_class'])->value('name');
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 服务单信息
     * @param $ids
     * @return string|\think\response\Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function fuwudan($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        $one_id = $this->request->get('id');
        $this->model = new One();
        $row = $this->model->get(['id'=>$one_id]);

        $this->view->assign("yw_belonger", $row['yw_belonger']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(["zuzhi"])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row['sign'] = 0;
                $sign = Db::name('sign')->where('orderid',$row['id'])->find();
                if($sign){
                    $row['sign'] = 1;
                }
            }
            $all_main_free =  Db::name('list_one')
                ->alias('one')
                ->join('zuzhi zuzhi','one.yw_class = zuzhi.id','left')
                ->where($where)
                ->group('one.id')->where('deletetime',)
                ->field('one.main_free,one.main_sum')
                ->select(false);
            $all = Db::query('select sum(c.main_free) as all_main_free,sum(c.main_sum) as all_main_sum from ('.$all_main_free.') as c');
            $all_main_free = round($all[0]['all_main_free'],2);
            $all_main_sum = round($all[0]['all_main_sum'],2);
            $result = array("total" => $list->total(), "rows" => $list->items(),'all_main_free'=>$all_main_free,'all_main_sum'=>$all_main_sum);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 浏览
     * @param $ids
     * @return void
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onedetails($ids = null){
        $this->model = new One();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row['car_register'] = date('Y-m-d',$row['car_register']);
        $row['plan_strattime'] = date('Y-m-d H:i:s',$row['plan_strattime']);
        $row['plan_endtime'] = date('Y-m-d H:i:s',$row['plan_endtime']);
        $this->view->assign('row', $row);
        $select = selectMenus_zuzhi($admin['zuzhi']);
        $this->assign('selectMenu',$select);
        $ren = db('admin')->where('zuzhi','in',$row['yw_class'])->select();
        $this->assign('ren',$ren);
        $ying = db('tong_files')->where('tong_id',$ids)->select();
        $this->assign('file', $ying);

        $yijian = db('yijian')->where('did',$ids)->select();
        $this->assign('yijian',$yijian);
        return $this->view->fetch();
    }
    /**
     * 服务单信息
     * @param $ids
     * @return string|\think\response\Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function baoan($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $one_id = $this->request->get('id');
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $buchang_money =  $this->model
                ->where($where)
                ->sum('yijue_money');
            $yugu_money = $this->model->where($where)->sum('yufu');
            $weijue_money = bcsub($yugu_money,$buchang_money,2);
            if($weijue_money < 0) $weijue_money = 0;
            $result = array("total" => $list->total(), "rows" => $list->items(),'buchang_money'=>$buchang_money,'weijue_money'=>$weijue_money);

            return json($result);
        }else{
            $this->model = new One();
            $row = $this->model->get(['id'=>$one_id]);
            $this->view->assign("yw_belonger", $row['yw_belonger']);
            return $this->view->fetch();
        }
    }
}
